/* 
 *  Author: Benedikt Niedermayr (2013)
 */


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>

unsigned int hflag = 0, wflag = 0, rflag = 0;
char *send_buff, *recv_buff;
char *interface;
int cnt = 0;
int res;
void parse_opts(int argc, char **argv)
{	
	int c;

	while((c = getopt(argc,argv,"hrw:c:d:")) != -1)
	{
		switch(c)
		{
			case 'h' : hflag = 1;                  				break;				/* help */
			case 'w' : wflag = 1; send_buff = optarg; 			break; 
			case 'r' : rflag = 1;                    			break;
			case 'c' : cnt = atoi(optarg);						break;
 			case 'd' : interface = optarg;						break; 
		}

	}
	if (hflag)
	{
		printf("Usage: %s [-w]/[-r] -c -d \n", argv[0]);		
		puts("-w		write");
		puts("-r		read");
		puts("-c 		number of bytes to be read/write");
		puts("-d		device file");
	exit(1);
		
	}
}

int main(int argc, char **argv)
{
	int fd;

	parse_opts(argc,argv);	
	fd = open(interface, O_RDWR);
	
	if(fd < 0) {
		printf("Datei konnte nicht geöffnet werden\n");
		return 0;
	} 

	if(wflag) {
		res = write(fd, send_buff, cnt);
		
		if((cnt != 0 && res == 0) || res < 0) {
			puts("Writing failed");
			exit(1);		
		}
		printf("%d Bytes written\n", res);
		
	} else if(rflag) {
		recv_buff = (char *) malloc(cnt + 1);
		res = read(fd, recv_buff, cnt);

		if((cnt != 0 && res == 0) || res <0 ) {
			puts("Writing failed");
			exit(1);		
		}		
		printf("Bytes read => %s\n", recv_buff);	
	}
	close(fd);

	
}
